package main

import (
	"code.google.com/p/go.net/websocket"
	"fmt"
	"time"
)

type connection struct {
	// The websocket connection.
	ws *websocket.Conn

	// Buffered channel of outbound messages.
	send chan string
}

func (c *connection) reader() {
	for {
		var message string
		err := websocket.Message.Receive(c.ws, &message)
		fmt.Print("reader: " + message + "\n")
		if err != nil {
			fmt.Println("reader-error: ", err.Error())
			break
		}
		h.broadcast <- message
	}
	c.ws.Close()
}

func (c *connection) writer() {
	for message := range c.send {
		err := websocket.Message.Send(c.ws, message)
		fmt.Print("write: " + message + "\n")
		if err != nil {
			fmt.Println("writer-error: ", err.Error())
			break
		}
	}
	c.ws.Close()
}

func (c *connection) updater() {
	ticker := time.Tick(1 * time.Second)
	for t := range ticker {
		err := websocket.Message.Send(c.ws, t.String())
		fmt.Printf("updater: " + t.String() + "\n")
		if err != nil {
			fmt.Println("error: ", err.Error())
			break
		}
	}
	c.ws.Close()
}

func cliHandler(cli *websocket.Conn) {
	c := &connection{send: make(chan string, 256), ws: cli}
	h.register <- c
	defer func() { h.unregister <- c }()
	go c.writer()
	c.reader()
}

func logHandler(log *websocket.Conn) {
	c := &connection{send: make(chan string, 256), ws: log}
	h.register <- c
	defer func() { h.unregister <- c }()
	//go c.writer()
	//var ticker *time.Ticker = time.NewTicker(1.0e9)
	go c.updater()
}
